package fr.snac.bm;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.widget.Toast;

import com.tumblr.jumblr.JumblrClient;
import com.tumblr.jumblr.types.PhotoPost;
import com.tumblr.jumblr.types.Post;

import fr.snac.serialization.Infos;
import fr.snac.serialization.InfosDeserializer;
import fr.snac.serialization.InfosSerializer;
import fr.snac.serialization.PostInfo;
import fr.snac.utils.Constants;
import fr.snac.utils.DateUtil;
import fr.snac.utils.FilesUtil;
import fr.snac.utils.TumblrClient;

public class AsyncSearch extends AsyncTask<Calendar, Void, IOException>{
	
	volatile BonjourActivity activity;
	
	long id = 0;
	AsyncPhoto asyncPhoto;
	String imageUSDate;
	Calendar imageDate;
	JumblrClient client;
	Infos infos;
	
	public AsyncSearch(BonjourActivity activity){
		this.activity = activity;
	}

	@Override
	protected IOException doInBackground(Calendar... params) {
		
		imageDate = params[0];
		imageUSDate = DateUtil.getUSDate(imageDate);
		
		boolean infosFileCreated = FilesUtil.isInfosFileCreated();
		ConnectivityManager manager = (ConnectivityManager)activity.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo network = manager.getActiveNetworkInfo();

		//if (network == null || !network.isConnected() || !network.isAvailable() || !infosFileCreated)
		if (network == null || !network.isConnected() || !network.isAvailable())
			return null;
		
		if (infosFileCreated){
			InfosDeserializer deSerializer = new InfosDeserializer();
			
			if (deSerializer.deSerialize()){
				infos = deSerializer.getInfos();
				
				if (infos.containsKey(imageUSDate)){
					PostInfo pi = infos.get(imageUSDate);
					id = pi.getId();
					
					return null;
				}
			}else
				infos = new Infos();
		}else
			infos = new Infos();
		
		client = TumblrClient.initializeClient();
		int offset;
		
		if (DateUtil.isSameDay(DateUtil.getToday(), imageDate))
			offset = 0;
		else
			offset = (DateUtil.daysBetweenDate(DateUtil.getToday(), imageDate) * -1) - 25;
		
		id = getPostId(client, infos, offset);
		
		if (id == 0)
			id = getPostId(client, infos, offset + 50);
		
		InfosSerializer serializer = new InfosSerializer(infos);
		serializer.serialize();
		
		return null;
	}
	
	@Override
	protected void onPostExecute(IOException result){
	
		BonjourActivity activity = this.activity;
		activity.asyncTask = null;
		
		asyncPhoto = new AsyncPhoto(activity, this, imageUSDate, id);
		asyncPhoto.execute();
		
		if (result != null){
			Toast.makeText(activity, result.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	
	private long getPostId(JumblrClient client, Infos infos, int offset){
		
		Map<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("type", "photo");
		queryParams.put("limit", 50);
		queryParams.put("offset", offset);
		
		List<Post> posts = client.blogPosts(Constants.BLOG_ADDRESS, queryParams);
		
		for (Post p : posts){
			PhotoPost pp = (PhotoPost)p;
			String dateToCheck = DateUtil.getUSDate(pp.getDateGMT());
			
			PostInfo pi = new PostInfo(pp.getId(), pp.getCaption(), dateToCheck);
			
			/*if (!infos.containsKey(dateToCheck)){
				infos.put(dateToCheck, pi);
			}*/
			
			if (imageUSDate.equals(dateToCheck))
				id = pi.getId();
		}
		
		return id;
	}
}
